#!/usr/bin/python
# -*- coding: utf-8 -*-
from sys import stderr, exit
from os import readlink, getuid, makedirs, system
from os.path import isfile, isdir, dirname, abspath, join as pjoin
try:
    from configparser import ConfigParser
except ImportError:
    from ConfigParser import ConfigParser

TOP_DIR  = abspath(pjoin(dirname(__file__), '..'))
EXEC_DIR = pjoin(TOP_DIR, 'seafile-server-latest')
SEAFILE_EXEC = pjoin(EXEC_DIR, 'seafile.sh')
SEAHUB_EXEC = pjoin(EXEC_DIR, 'seahub.sh')

IS_SQLITE = isfile(pjoin(TOP_DIR, 'seahub.db'))


def print_err(msg):
    try:
        print(msg, file=stderr)
    except SyntaxError:
        print >> stderr, msg


def get_empty_service_config():
    cfg = ConfigParser()
    cfg.optionxform = lambda s: s
    cfg.add_section('Unit')
    cfg.add_section('Service')
    cfg.add_section('Install')
    return cfg


def create_seafile_config():
    unit_after = 'network.target' if IS_SQLITE else 'network.target mysql.service'
    cfg = get_empty_service_config()
    cfg.set('Unit', 'Description', 'Seafile Service')
    cfg.set('Unit', 'After', unit_after)
    cfg.set('Service', 'Type', 'oneshot')
    cfg.set('Service', 'ExecStart', '%s start' % SEAFILE_EXEC)
    cfg.set('Service', 'ExecStop', '%s stop' % SEAFILE_EXEC)
    cfg.set('Service', 'User', '%i')
    cfg.set('Service', 'Group', '%i')
    cfg.set('Service', 'RemainAfterExit', 'yes')
    cfg.set('Install', 'WantedBy', 'multi-user.target')

    return cfg


def create_seahub_config():
    cfg = create_seafile_config()
    cfg.set('Unit', 'Description', 'Seahub Service')
    cfg.set('Unit', 'After', 'seafile@%i.service')
    cfg.set('Service', 'ExecStart', '%s start' % SEAHUB_EXEC)
    cfg.set('Service', 'ExecStop', '%s stop' % SEAHUB_EXEC)

    return cfg


def main():
    if getuid() != 0:
        print_err("\033[1;31mError:\033[22m Please run as root or with sudo!\033[0m")
        exit(1)

    unit_dir = '/usr/local/lib/systemd/system'
    if not isdir(unit_dir):
        makedirs(unit_dir)

    try:
        seafile_cfg = create_seafile_config()
        seafile_unit_file = pjoin(unit_dir, 'seafile@.service')
        with open(seafile_unit_file, 'w') as f:
            seafile_cfg.write(f)

        seahub_cfg = create_seahub_config()
        seahub_unit_file = pjoin(unit_dir, 'seahub@.service')
        with open(seahub_unit_file, 'w') as f:
            seahub_cfg.write(f)

        system('systemctl daemon-reload')
        print("Successed!")
    except Exception as e:
        raise e

if __name__ == '__main__':
    main()
